package com.kfm.base.net;

import java.io.*;
import java.net.*;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ChatServer {

    public static void main(String[] args) {
        try (ServerSocket server = new ServerSocket(8888);){

            // 存所有的用户
            ConcurrentHashMap<String, Socket> users = new ConcurrentHashMap<>();

            // 处理用户消息
            ThreadPoolExecutor taskPool = new ThreadPoolExecutor(10, 60, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.AbortPolicy());

            while (true){
                Socket user = server.accept();
                users.put(user.getInetAddress().getHostAddress(), user);

                System.out.println("用户：" + user.getInetAddress().getHostAddress() + " 进入聊天室");

                taskPool.execute(() -> {
                    try {
                        InputStream inputStream = user.getInputStream();

                        byte[] bytes = inputStream.readAllBytes();

                        String msg = new String(bytes);
                        String s = user.getInetAddress() + " 发送了： " + msg;
                        System.out.println(s);

                        Collection<Socket> values = users.values();

                        for (Socket client : values){

                            OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
                            BufferedWriter bw = new BufferedWriter(writer);
                            bw.write(s);
                            bw.newLine();
                            bw.flush();

                            bw.close();
                        }


                    } catch (IOException e) {
                        users.remove(user.getInetAddress().getHostAddress());
                        throw new RuntimeException(e);
                    }
                });
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
